package com.joejag.mavenstats.client.views.sidebar.children;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.*;
import com.joejag.mavenstats.client.MavenStats;
import com.joejag.mavenstats.client.service.ReportsService;
import com.joejag.mavenstats.client.service.ReportsServiceAsync;

import java.util.List;

public class Reports extends Composite implements TreeListener
{
  private Tree tree;

  public Reports(final Images images)
  {
    tree = new Tree(images);
    tree.addTreeListener(this);

    refreshTree(images);

    initWidget(tree);
  }

  public void refreshTree(final Images images)
  {
    ReportsServiceAsync serviceAsync = ReportsService.App.getInstance();
    serviceAsync.getReportNames(new AsyncCallback()
    {
      public void onFailure(Throwable throwable)
      {
      }

      public void onSuccess(Object o)
      {
        tree.clear();
        List reports = (List) o;
        for (int i = 0; i < reports.size(); i++)
          tree.addItem(new TreeItem("<span>" + images.report().getHTML() + reports.get(i) + "</span>"));
      }
    });
  }

  public void onTreeItemSelected(TreeItem treeItem)
  {
    MavenStats.instance().displayReport(treeItem.getText());
  }

  public void onTreeItemStateChanged(TreeItem treeItem)
  {
  }

  public interface Images extends ImageBundle, TreeImages
  {
    /**
     * @gwt.resource com/joejag/mavenstats/client/images/plugins/report.png
     */
    AbstractImagePrototype report();
  }
}
